<template>
  <div class="center">
    <!-- 头部 -->
    <div class="table_header flex flex_bet flex-wrap">
      <div class="table_button">
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="Refresh"></el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="toAddTime(1)">按时间段添加</el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="toAddTime(2)">按时长添加</el-button>
      </div>
      <div class="table_searchs flex felx_align">
        <div class="table_search flex">
          <el-input placeholder="搜索" v-model="searchTable" class="input-with-select" size="small">
            <el-select v-model="select" slot="prepend" placeholder="请选择" class="table_select" style="width:105px">
              <el-option label="批次" value="1"></el-option>
              <el-option label="归属" value="2"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="idnameSearch"></el-button>
          </el-input>
        </div>
        <dynamicTable :checkboxVal="checkboxVal" @alter="alterCheckbok"/>
      </div>
    </div>
    <!-- 设备归属管理table -->
    <el-table stripe style="width: 100%" :data="tableData" :key="key" border fit highlight-current-row ref="tableDataRef" max-height="545">
      <el-table-column v-if="colData[0].istrue" min-width="50" align="center" prop="id" label="id"></el-table-column>
      <el-table-column v-if="colData[0].istrue" min-width="100" align="center" prop="admin_name" label="归属"></el-table-column>
      <el-table-column v-if="colData[0].istrue" min-width="100" align="center" prop="time_type" label="添加方式">
        <template slot-scope="scope">
          <span v-if="scope.row.time_type===1">按时间段</span>
          <span v-else>按可用时长</span>
        </template>
      </el-table-column>
      <el-table-column v-if="colData[1].istrue" min-width="130" align="center"  label="批次/sn">
        <template slot-scope="scope">
         <span v-if="scope.row.belong_type===1">{{scope.row.batchName}}</span>
          <span v-else>{{scope.row.sn}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="100" align="center" prop="sn" label="应用">
        <template slot-scope="scope">
          <span v-if="scope.row.is_all_app===1">全部应用</span>
          <span v-else>{{scope.row.appName}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="120" align="center" prop="sn" label="开放时间段">
        <template slot-scope="scope">
          <span>{{scope.row.start_time}}至{{scope.row.end_time}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="120" align="center" prop="sn" label="可用时长">
        <template slot-scope="scope">
          <span>{{scope.row.time_type === 2 ?scope.row.remain_time + '分钟' : '--'}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="180" align="center" prop="sn" label="重复日期">
        <template slot-scope="scope">
          <span v-if="scope.row.is_repeat===-1">不重复</span>
          <span v-else>{{scope.row.weekStr}}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="colData[3].istrue" min-width="140" align="center" prop="create_time" label="创建时间">
        <template slot-scope="scope">{{ scope.row.create_time| newDate }}</template>
      </el-table-column>
      <el-table-column min-width="150" align="center" prop="log" label="操作">
        <template slot-scope="scope">
          <el-row>
            <el-button size="mini" type="primary" @click="getqueryIdTimeControl(scope.row)">编辑</el-button>
            <el-button size="mini" @click="deleteShow(scope.row.id)">删除</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="paging">
      <el-pagination :current-page.sync="listQuery.startSize" background @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[10, 50, 100, 200]" layout="total, sizes, prev, pager, next, jumper" :total="total" :page-size="listQuery.pageSize">
      </el-pagination>
    </div>
    <!-- 添加dialog表单 -->
    <el-dialog :title="editSubjects ? '平板使用时间管控' : '编辑'" :visible.sync="dialogFormVisible" @close="addFormclose" :close-on-click-modal="false" :close-on-press-escape="false" width="40%">
      <el-form :model="addForm" ref="ruleForm" :rules="rules" style="padding-top:0">
        <el-form-item label="类型:" label-width="100px" prop="belong_type">
          <el-radio-group v-model="addForm.belong_type" :disabled="!editSubjects">
            <el-radio :label="1">批次</el-radio>
            <el-radio :label="2">sn</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="批次:" label-width="100px" prop="batch" v-if="addForm.belong_type===1">
          <el-select v-model="addForm.batch" placeholder="没有选中任何项" class="add_select" filterable multiple>
            <el-option v-for="item in batchOptions" :key="item.id" :label="item.batch" :value="item.id.toString()"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="SN:" label-width="100px" prop="sn" v-else>
          <el-input placeholder="请输入sn" v-model="addForm.sn" clearable minlength="12"></el-input>
        </el-form-item>
        <el-form-item label="可用时间" label-width="100px" prop="available_time" v-if="addForm.time_type===1">
          <el-time-picker
            is-range
            v-model="addForm.available_time"
            format="HH:mm"
            value-format="timestamp"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            placeholder="选择时间范围"
          >
          </el-time-picker>
        </el-form-item>
        <el-form-item label="可用时长:" label-width="100px" prop="remain_time" v-else>
          <el-input-number v-model="addForm.remain_time" :min="0" :max="1440" placeholder="请输入分钟数"></el-input-number>
          <i class="pl-8 ">{{ formattedremain_time }}</i>
        </el-form-item>
        <el-form-item label="可用应用:" label-width="100px" prop="is_all_app">
          <el-radio-group v-model="addForm.is_all_app">
            <el-radio :label="1">全部应用</el-radio>
            <el-radio :label="-1">部分应用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="应用:" label-width="100px" prop="app_package" v-if="addForm.is_all_app===-1">
          <el-select v-model="addForm.app_package" placeholder="请选择" multiple clearable collapse-tags filterable>
            <el-option-group
              v-for="group in appList"
              :key="group.label"
              :label="group.label">
              <el-option
                v-for="item in group.options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-option-group>
          </el-select>
        </el-form-item>
        <el-form-item label="是否重复:" label-width="100px" prop="is_repeat">
          <el-radio-group v-model="addForm.is_repeat">
            <el-radio :label="1">重复</el-radio>
            <el-radio :label="-1">不重复</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label-width="100px" v-if="addForm.is_repeat===1" prop="weekdays">
          <el-checkbox-group v-model="addForm.weekdays">
            <el-checkbox v-for="item in weekList" :label="item.value" :key="item.value">{{ item.label }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false" size="mini" round>取 消</el-button>
        <el-button v-if="editSubjects" type="primary" @click="getaddTimeControl('ruleForm')" size="mini" round>确 定
        </el-button>
        <el-button v-else type="primary" @click="geteditTimeControl('ruleForm')" size="mini" round>编辑</el-button>
      </div>
    </el-dialog>
    <!-- 删除弹窗 -->
    <delete-Dialog title="" :visible.sync="deleteDialogs.show" width="25%" top="40vh" @deleteEvents="deleteEvents" :deleteText="deleteDialogs.deleteText"/>
  </div>
</template>

<script>
import dynamicTable from "@/components/DynamicTable";
import deleteDialog from "@/components/deleteDialog";
import {
  queryTimeControl,
  addTimeControl,
  deleteTimeControl,
  editTimeControl
} from "@/api/deployment.js";
import {getBatchTwo} from "@/api/equipment.js";
import tableMini from '@/utils/tableMini.js'
import {getAllAppOptions} from "@/api/appUpdate";
import {querySnAppInfo} from "@/api/wxAccounts";

export default {
  mixins: [tableMini],
  components: {dynamicTable, deleteDialog},
  data() {
    return {
      checkboxVal: ["归属", "批次", "开始-结束时间", "创建时间"],
      tableData: [],
      select: "1", //搜索条件
      listQuery: {
        startSize: 1,
        pageSize: 10,
        userId: localStorage.getItem("ID"),
        batch: undefined,
        username: undefined
      },
      //添加按钮控制
      dialogFormVisible: false,
      //编辑按钮控制
      editSubjects: true,
      //浏览器专题id
      subjectId: 0,
      batchOptions: [],
      snOptions: [],
      //添加表单
      addForm: {
        belong_type: 1, //归属类型 【1：批次 2：sn】
        batch: "",
        sn: "",
        available_time: [1745193600000, 1745229600000],
        is_all_app: 1,
        app_package: [],
        is_repeat: 1,
        weekdays: [],
        remain_time: 0,
        time_type: 1, //1：按可用时间段 2:按剩余时长
      },
      rules: {
        belong_type: [{required: true, message: "请选择类型", trigger: "blur"}],
        is_all_app: [{required: true, message: "请选择应用", trigger: "blur"}],
        is_repeat: [{required: true, message: "请选择是否重复", trigger: "blur"}],
      },
      weekList: [
        {label: '周一', value: 1},
        {label: '周二', value: 2},
        {label: '周三', value: 3},
        {label: '周四', value: 4},
        {label: '周五', value: 5},
        {label: '周六', value: 6},
        {label: '周日', value: 7},
      ],
      appList: [],
    }
  },
  created() {
    this.getTabularData()
    this.getBatchTwos()
    this.getAllAppOptionsControl()
  },
  computed: {
    formattedremain_time() {
      const totalMinutes = this.addForm.remain_time;
      const hours = Math.floor(totalMinutes / 60);
      const minutes = totalMinutes % 60;
      return `${hours}小时${minutes}分钟`;
    }
  },
  methods: {
    getTabularData() {
      queryTimeControl(this.listQuery).then(res => {
        this.tableData = res.data
        this.total = res.total
      }).catch(err => {
        this.tableData = []
        this.total = 0
      })
    },
    //删除按钮事件
    deleteEvents() {
      let params = {
        userId: localStorage.getItem("ID"),
        last_ip: sessionStorage.getItem("Ip"),
        id: this.deleteDialogs.deleteId
      }
      deleteTimeControl(params).then(res => {
        this.$message.success(res.msg)
        this.getTabularData()
      })
    },
    //添加按钮事件
    toAddTime(time_type) {
      this.editSubjects = true
      this.dialogFormVisible = true
      this.addForm.time_type = time_type
    },
    //增加时间管控
    getaddTimeControl(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let addForm = JSON.parse(JSON.stringify(this.addForm))
          addTimeControl(addForm).then(res => {
            this.$message.success(res.msg)
            this.getTabularData()
            this.dialogFormVisible = false
          }).catch(err => {
          })
        } else {
          return false
        }
      })

    },
    //编辑
    geteditTimeControl(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let addForm = JSON.parse(JSON.stringify(this.addForm))
          addForm.id = this.subjectId
          editTimeControl(addForm).then(res => {
            this.dialogFormVisible = false
            this.$message.success(res.msg)
            this.getTabularData()
          }).catch(err => {
          })
        } else {
          return false
        }
      })
    },
    //根据ID查询信息
    getqueryIdTimeControl(row) {
      this.editSubjects = false
      this.dialogFormVisible = true
      this.addForm = {
        belong_type: row.belong_type, //归属类型 【1：批次 2：sn】
        batch: row.batchArr,
        sn: row.sn,
        available_time: row.available_time,
        is_all_app: row.is_all_app,
        app_package: row.app_package,
        is_repeat: row.is_repeat,
        weekdays: row.weekdays,
        remain_time: row.remain_time,
        time_type: row.time_type, //1：按可用时间段 2:按剩余时长
      }
      this.subjectId = row.id

    },
    //根据ID获取批次列表
    getBatchTwos() {
      let data = {userId: localStorage.getItem("ID")}
      getBatchTwo(data).then(res => {
        this.batchOptions = res.data
      }).catch(err => {
        this.batchOptions = []
      })
    },
    getAllAppOptionsControl() {
      getAllAppOptions().then(res => {
        this.appList = res.data
      }).catch(err => {
        this.appList = []
      })
    },
    //搜索,1:网址，2:类型
    idnameSearch() {
      if (!this.select) return this.$message.warning("请先选择查询条件");
      this.listQuery.startSize = 1
      this.listQuery.pageSize = 10
      switch (this.select) {
        case '1':
          let search = this.batchOptions.filter(key => key.batch == this.searchTable).map(item => item.id)[0]
          this.listQuery.batch = search ? search : this.searchTable
          this.getTabularData();
          break;
        case '2':
          this.listQuery.username = this.searchTable
          this.getTabularData();
          break;
      }
    },
    //编辑添加表单关闭事件
    addFormclose() {
      this.$nextTick(() => {
        this.$refs.ruleForm.resetFields();
        this.addForm = this.$options.data().addForm
        this.timesList = this.$options.data().timesList
      })
    },
  }
}
</script>
